import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';
import 'package:provider/provider.dart';
import '../models/purchase_item.dart';
import '../providers/user_provider.dart';
import '../main.dart';  // 导入 main.dart 以使用 navigatorKey

class PurchaseService extends ChangeNotifier {
  static final PurchaseService _instance = PurchaseService._internal();
  factory PurchaseService() => _instance;
  PurchaseService._internal();

  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  final StreamController<List<PurchaseItem>> _itemsController = StreamController<List<PurchaseItem>>.broadcast();
  final StreamController<bool> _loadingController = StreamController<bool>.broadcast();
  final StreamController<bool> _purchaseCompleteController = StreamController<bool>.broadcast();

  Stream<List<PurchaseItem>> get itemsStream => _itemsController.stream;
  Stream<bool> get loadingStream => _loadingController.stream;
  Stream<bool> get purchaseCompleteStream => _purchaseCompleteController.stream;

  List<ProductDetails> _products = [];
  List<ProductDetails> get products => _products;
  bool _isAvailable = false;
  bool get isAvailable => _isAvailable;
  bool _isPurchasing = false;
  bool get isPurchasing => _isPurchasing;

  // 商品ID列表
  static const Set<String> _productIds = {
    '446200', // 100 coins
    '446201', // 500 coins
    '446202', // 1200 coins
    '446203', // 2500 coins
    '446204', // 7000 coins
    '446205', // 15000 coins
    '446206', // 500 coins - discount
    '446207', // 1200 coins - discount
    '446208', // 2500 coins - discount
    '446209', // 7000 coins - discount
    '446210', // 15000 coins - discount
  };

  Future<void> initialize() async {
    _isAvailable = await _inAppPurchase.isAvailable();
    if (!_isAvailable) {
      notifyListeners();
      debugPrint('In-app purchase is not available');
      return;
    }

    _inAppPurchase.purchaseStream.listen(_handlePurchaseUpdates);
    await loadProducts();
  }

  Future<List<PurchaseItem>> loadProducts() async {
    try {
      _loadingController.add(true);
      
      final ProductDetailsResponse response = await _inAppPurchase.queryProductDetails(_productIds);
      
      if (response.notFoundIDs.isNotEmpty) {
        debugPrint('Products not found: ${response.notFoundIDs.join(', ')}');
      }
      
      // 按照 _productIds 的顺序排序商品
      final List<PurchaseItem> items = response.productDetails
          .map((product) => PurchaseItem.fromProductDetails(product))
          .toList()
        ..sort((a, b) {
          final indexA = _productIds.toList().indexOf(a.id);
          final indexB = _productIds.toList().indexOf(b.id);
          return indexA.compareTo(indexB);
        });
      
      _products = response.productDetails;
      _itemsController.add(items);
      notifyListeners();
      return items;
    } catch (e) {
      debugPrint('Failed to load products: $e');
      return [];
    } finally {
      _loadingController.add(false);
    }
  }

  Future<bool> purchaseProduct(PurchaseItem item) async {
    if (_isPurchasing) {
      debugPrint('Please wait for the current purchase to complete');
      return false;
    }

    try {
      _isPurchasing = true;
      _loadingController.add(true);
      
      debugPrint('Starting purchase for product: ${item.id}');
      
      final PurchaseParam purchaseParam = PurchaseParam(
        productDetails: ProductDetails(
          id: item.id,
          title: item.title,
          description: item.description,
          price: item.priceString,
          rawPrice: item.price,
          currencyCode: item.currencyCode,
        ),
        applicationUserName: "Snug",
      );
      
      final bool success = await _inAppPurchase.buyConsumable(
          purchaseParam: purchaseParam
      );
      
      if (!success) {
        debugPrint('Purchase failed: buyConsumable returned false');
        _isPurchasing = false;
        _loadingController.add(false);
      } else {
        debugPrint('Purchase initiated successfully');
      }
      
      return success;
    } catch (e) {
      debugPrint('Purchase failed with error: $e');
      _isPurchasing = false;
      _loadingController.add(false);
      return false;
    }
  }

  void _handlePurchaseUpdates(List<PurchaseDetails> purchaseDetailsList) async {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      debugPrint('Purchase status update: ${purchaseDetails.status}');
      
      if (purchaseDetails.status == PurchaseStatus.pending) {
        _loadingController.add(true);
      } else if (purchaseDetails.status == PurchaseStatus.error) {
        debugPrint('Purchase error: ${purchaseDetails.error?.message}');
        await _inAppPurchase.completePurchase(purchaseDetails);
        _isPurchasing = false;
        _loadingController.add(false);
      } else if (purchaseDetails.status == PurchaseStatus.purchased ||
          purchaseDetails.status == PurchaseStatus.restored) {
        await _handleSuccessfulPurchase(purchaseDetails);
      } else if (purchaseDetails.status == PurchaseStatus.canceled) {
        debugPrint('Purchase was canceled by user');
        await _inAppPurchase.completePurchase(purchaseDetails);
        _isPurchasing = false;
        _loadingController.add(false);
      }
    }
  }

  Future<void> _handleSuccessfulPurchase(PurchaseDetails purchaseDetails) async {
    try {
      debugPrint('Processing successful purchase for product: ${purchaseDetails.productID}');
      
      // 从商品ID中获取金币数量
      final purchaseItem = _products.firstWhere(
        (product) => product.id == purchaseDetails.productID,
        orElse: () => throw Exception('Product not found: ${purchaseDetails.productID}'),
      );
      
      final coins = PurchaseItem.fromProductDetails(purchaseItem).coins;
      debugPrint('Adding $coins coins to user account');
      
      if (coins != null) {
        // 获取 UserProvider 实例并更新金币数量
        final context = navigatorKey.currentContext;
        if (context != null) {
          final userProvider = Provider.of<UserProvider>(context, listen: false);
          userProvider.addCoins(coins);
          
          // 通知购买成功
          _purchaseCompleteController.add(true);
          debugPrint('Purchase completed successfully');
        } else {
          debugPrint('Warning: Could not get context for updating coins');
        }
      } else {
        debugPrint('Warning: coins value is null for product ${purchaseDetails.productID}');
      }
      
      await _inAppPurchase.completePurchase(purchaseDetails);
      _isPurchasing = false;
      _loadingController.add(false);
    } catch (e) {
      debugPrint('Failed to complete purchase: $e');
      _isPurchasing = false;
      _loadingController.add(false);
    }
  }

  Future<void> restorePurchases() async {
    try {
      await _inAppPurchase.restorePurchases();
    } catch (e) {
      debugPrint('Error restoring purchases: $e');
    }
  }

  @override
  void dispose() {
    _itemsController.close();
    _loadingController.close();
    _purchaseCompleteController.close();
    super.dispose();
  }
} 